/*
 * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.bpel.services;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.bpel.BPELConstants;
import org.wso2.carbon.core.AbstractAdmin;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.bpel.services.types.UploadedFileItem;


import javax.activation.DataHandler;
import java.io.*;
import java.nio.channels.FileChannel;

/**
 * BPEL package uploader admin service
 */
public class BPELUploader extends AbstractAdmin {
    private static final Log log = LogFactory.getLog(BPELUploader.class);

    public void uploadService(UploadedFileItem[] fileItems) throws AxisFault {
        try {

            //First lets filter for jar resources
            ConfigurationContext configurationContext = getConfigContext();
            String repo = configurationContext.getAxisConfiguration().getRepository().getPath();


            if (CarbonUtils.isURL(repo)) {
                throw new AxisFault("URL Repositories are not supported: " + repo);
            }

            //Writting the artifacts to the proper location
            String bpelDirectory = repo + File.separator + BPELConstants.BPEL_REPO_DIRECTORY;

            String bpelTemp = CarbonUtils.getCarbonHome() + BPELConstants.BPEL_PACKAGE_TEMP_DIRECTORY;
            File bpelTempDir = new File(bpelTemp);
            if (!bpelTempDir.exists()) {
                bpelTempDir.mkdirs();
            }

            File bpelDir = new File(bpelDirectory);
            if (!bpelDir.exists()) {
                bpelDir.mkdirs();
            }

            for (UploadedFileItem uploadedFile : fileItems) {
                String fileName = uploadedFile.getFileName();

                if (fileName == null || fileName.equals(""))
                    throw new AxisFault("Invalid file name. File name is not available");

                if (uploadedFile.getFileType().equals(BPELConstants.BPEL_PACKAGE_EXTENSION)) {
                    writeResource(uploadedFile.getDataHandler(), bpelTemp, fileName, bpelDir);
                } else {
                    throw new AxisFault("Invalid file type : " + uploadedFile.getFileType() + " ." +
                                        BPELConstants.BPEL_PACKAGE_EXTENSION +
                                        " file type is expected");
                }
            }
        } catch (Exception e) {
            throw new AxisFault("Error occurred while uploading service artifacts", e);
        }
    }

    private void writeResource(DataHandler dataHandler, String destPath, String fileName,
                               File bpelDest) throws IOException {
        File destFile = new File(destPath, fileName);
        FileOutputStream fos = null;
        FileChannel out = null;
        FileChannel in = null;
        try {
            fos = new FileOutputStream(destFile);
            /* File stream is copied to a temp directory in order handle hot deployment issue
               occurred in windows */
            dataHandler.writeTo(fos);
            out = new FileOutputStream(bpelDest + File.separator + fileName).getChannel();
            in = new FileInputStream(destFile).getChannel();
            out.write(in.map(FileChannel.MapMode.READ_ONLY, 0, in.size()));
        } catch (FileNotFoundException e) {
            log.error("Cannot find the file", e);
            throw e;
        } catch (IOException e) {
            log.error("IO error.");
            throw e;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.warn("Can't close file streams.", e);
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.warn("Can't close file streams.", e);
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.warn("Can't close file streams.", e);
            }
        }

        boolean isDeleted = destFile.delete();
        if (!isDeleted) {
            log.warn("temp file: " + destFile.getAbsolutePath() +
                                            " deletion failed, scheduled deletion on server exit.");
            destFile.deleteOnExit();
        }
    }
}
